package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单微服务
 *
 *      去结算
 *      提交订单
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderInfoService;

    //查询商品清单 交易号
    //收货地址（已经写在用户微服务中了,不需要在写)
    @GetMapping("/trade")
    public Map<String, Object> trade(HttpServletRequest request){
        Map<String, Object> result = null;
        //1.查询商品清单
        List<CartInfo> cartListChecked = cartFeignClient.getCartListChecked();

        if (!CollectionUtils.isEmpty(cartListChecked)){
            result = new HashMap<>();

            //需要的集合是List<OrderDetail>
            List<OrderDetail> orderDetailList = cartListChecked.stream().map(cartInfo -> {
                OrderDetail detail = new OrderDetail();
                detail.setImgUrl(cartInfo.getImgUrl());
                detail.setSkuName(cartInfo.getSkuName());
                detail.setOrderPrice(cartInfo.getSkuPrice());
                detail.setSkuNum(cartInfo.getSkuNum());
                detail.setSkuId(cartInfo.getSkuId());
                return detail;
            }).collect(Collectors.toList());
            result.put("detailArrayList",orderDetailList);

            //2.总件数
            long totalNum = orderDetailList.stream().collect(
                    Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
            result.put("totalNum",totalNum);

            //3.总金额
            BigDecimal totalAmount = new BigDecimal(0);
            for (OrderDetail orderDetail : orderDetailList) {
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                totalAmount = totalAmount.add(orderPrice.multiply(new BigDecimal(orderDetail.getSkuNum())));
            };
            result.put("totalAmount",totalAmount);

            //4.交易号
            String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
            result.put("tradeNo",tradeNo);
            String userId = AuthContextHolder.getUserId(request);
            redisTemplate.opsForValue().set("tradeNo:" + userId,tradeNo);
        }

        return result;
    }


    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo,HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);
        //1.校验交易号或订单号是否正确，防止二次提交
        if (StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("非法操作");
        }
        Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
        //如果没有值，就表示订单已经提交过了
        if (null == o){
            return Result.fail().message("请勿重复提交");
        } else if (!tradeNo.equals(o)){
            return Result.fail().message("非法操作");
        }
        //交易号正确
        redisTemplate.delete("tradeNo:" + userId);
        //2.校验库存（远程调用仓库系统）
        //有库存，购买数量小于（剩余库存-锁定）就是无库存，反之也一样
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                //校验库存
                boolean flag = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
                if (!flag){
                    return Result.fail().message(orderDetail.getSkuName() + "[商品已售完]");
                }
            }
        }


        //保存订单表 订单详情表
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }


    //根据订单id，查询订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //由仓库发出的拆单请求
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        //查看库存系统   （拆单说明文档）
        //1.开始拆单
        /*List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //2.拆单后集合
        List<Map> listMap = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());*/

        List<Map> listMap =orderInfoService.orderSplit1(orderId,wareSkuMap);
        //转成字符串
        return JSONObject.toJSONString(listMap);
    }

}
